import sys
import os
import sqlite3
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
from PyQt5.QtWidgets import (QApplication, QMainWindow, QTableWidget, QTableWidgetItem, 
                            QPushButton, QComboBox, QLineEdit, QLabel, QHBoxLayout, 
                            QVBoxLayout, QWidget, QTabWidget, QDialog, QFormLayout,
                            QInputDialog, QFileDialog, QDoubleSpinBox, QDateEdit,
                            QAction, QMessageBox, QHeaderView, QAbstractItemView,
                            QListWidget, QStatusBar, QAbstractButton, QToolButton,
                            QCheckBox, QFrame, QGroupBox, QStyleFactory)
from PyQt5.QtCore import Qt, QDate
from PyQt5.QtGui import QIcon, QPixmap, QFont, QColor
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

# 设置中文字体支持
def setup_chinese_font():
    # 尝试使用系统支持的中文字体
    chinese_fonts = ['SimHei', 'Microsoft YaHei', 'KaiTi', 'FangSong', 'STSong', 'STKaiti', 'STFangsong', 
                     'Droid Sans Fallback', 'WenQuanYi Micro Hei']
    
    # 检查系统可用的中文字体
    available_fonts = [f.name for f in mpl.font_manager.fontManager.ttflist]
    
    # 选择第一个可用的中文字体
    for font in chinese_fonts:
        if font in available_fonts:
            plt.rcParams['font.family'] = font
            plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题
            return
    
    # 如果没有找到中文字体，尝试使用默认字体
    plt.rcParams['font.family'] = 'sans-serif'
    plt.rcParams['axes.unicode_minus'] = False

# 在程序启动前设置中文字体
setup_chinese_font()

class DatabaseManager:
    """管理SQLite数据库连接和操作"""
    def __init__(self, db_path="finance.db"):
        self.db_path = db_path
        self.conn = None
        self.cursor = None
        
        # 初始化数据库
        self.initialize_database()
    
    def initialize_database(self):
        """初始化数据库和表结构"""
        self.connect()
        
        # 创建交易记录表
        self.cursor.execute("""
        CREATE TABLE IF NOT EXISTS transactions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            date TEXT NOT NULL,
            type TEXT NOT NULL,
            category TEXT NOT NULL,
            description TEXT NOT NULL,
            amount REAL NOT NULL,
            account TEXT NOT NULL,
            note TEXT DEFAULT ''
        )
        """)
        
        # 创建分类表
        self.cursor.execute("""
        CREATE TABLE IF NOT EXISTS categories (
            name TEXT PRIMARY KEY
        )
        """)
        
        # 创建账户表
        self.cursor.execute("""
        CREATE TABLE IF NOT EXISTS accounts (
            name TEXT PRIMARY KEY
        )
        """)
        
        # 提交更改
        self.conn.commit()
        
        # 添加默认数据（如果表为空）
        self.add_default_data()
    
    def add_default_data(self):
        """添加默认数据（如果表为空）"""
        # 检查分类表是否为空
        self.cursor.execute("SELECT COUNT(*) FROM categories")
        if self.cursor.fetchone()[0] == 0:
            default_categories = ["购物", "餐饮", "交通", "住宿", "娱乐", "医疗", "教育"]
            for category in default_categories:
                self.cursor.execute("INSERT OR IGNORE INTO categories (name) VALUES (?)", (category,))
        
        # 检查账户表是否为空
        self.cursor.execute("SELECT COUNT(*) FROM accounts")
        if self.cursor.fetchone()[0] == 0:
            default_accounts = ["抖音月付", "招商银行", "支付宝", "微信支付", "现金", "工商银行"]
            for account in default_accounts:
                self.cursor.execute("INSERT OR IGNORE INTO accounts (name) VALUES (?)", (account,))
        
        # 检查交易记录表是否为空
        self.cursor.execute("SELECT COUNT(*) FROM transactions")
        if self.cursor.fetchone()[0] == 0:
            # 添加默认交易记录
            default_transactions = [
                ("2025-06-30", "收入", "工资", "工资", 10000.00, "招商银行", "基本工资"),
                ("2025-07-01", "支出", "购物", "小米手机", 541.58, "抖音月付", ""),
                ("2025-07-01", "支出", "购物", "减肥胶囊", 279.80, "抖音月付", ""),
                ("2025-07-01", "支出", "购物", "21金维他", 59.70, "抖音月付", ""),
                ("2025-07-01", "支出", "餐饮", "山东济铁", 14.90, "招商银行", ""),
                ("2025-07-01", "支出", "餐饮", "美团-烤肉", 24.90, "招商银行", ""),
                ("2025-07-01", "支出", "餐饮", "美团-利峰", 26.00, "招商银行", ""),
                ("2025-07-01", "支出", "餐饮", "美团-麦当劳", 43.40, "招商银行", ""),
                ("2025-07-01", "支出", "餐饮", "美团-好适口", 18.20, "招商银行", ""),
                ("2025-06-23", "支出", "交通", "高德打车", 230.04, "招商银行", "去新疆出差到北京南站"),
                ("2025-06-23", "支出", "住宿", "麗枫酒店", 718.95, "招商银行", "出差酒店"),
                ("2025-06-25", "支出", "交通", "库尔勒-乌...", 108.00, "招商银行", ""),
                ("2025-06-27", "支出", "餐饮", "美团-东北...", 17.30, "招商银行", ""),
                ("2025-06-28", "支出", "餐饮", "美团-肯德基", 39.90, "招商银行", ""),
                ("2025-07-08", "支出", "餐饮", "美团-晋福...", 17.20, "招商银行", ""),
                ("2025-07-08", "支出", "餐饮", "美团-韩式...", 38.80, "招商银行", ""),
                ("2025-07-05", "收入", "奖金", "项目奖金", 5000.00, "招商银行", "Q2项目奖金")
            ]
            for trans in default_transactions:
                self.cursor.execute("""
                INSERT INTO transactions (date, type, category, description, amount, account, note)
                VALUES (?, ?, ?, ?, ?, ?, ?)
                """, trans)
        
        self.conn.commit()
    
    def connect(self):
        """连接到数据库"""
        self.conn = sqlite3.connect(self.db_path)
        self.cursor = self.conn.cursor()
    
    def disconnect(self):
        """断开数据库连接"""
        if self.conn:
            self.conn.close()
            self.conn = None
            self.cursor = None
    
    def execute_query(self, query, params=()):
        """执行查询并返回结果"""
        self.cursor.execute(query, params)
        return self.cursor.fetchall()
    
    def execute_update(self, query, params=()):
        """执行更新操作并提交"""
        self.cursor.execute(query, params)
        self.conn.commit()
        return self.cursor.rowcount
    
    def get_transactions(self):
        """获取所有交易记录"""
        return self.execute_query("SELECT * FROM transactions ORDER BY date DESC")
    
    def get_categories(self):
        """获取所有分类"""
        return [row[0] for row in self.execute_query("SELECT name FROM categories")]
    
    def get_accounts(self):
        """获取所有账户"""
        return [row[0] for row in self.execute_query("SELECT name FROM accounts")]
    
    def add_transaction(self, date, type_, category, description, amount, account, note=""):
        """添加新交易记录"""
        self.execute_update(
            "INSERT INTO transactions (date, type, category, description, amount, account, note) VALUES (?, ?, ?, ?, ?, ?, ?)",
            (date, type_, category, description, amount, account, note)
        )
        return self.cursor.lastrowid
    
    def update_transaction(self, id, date, type_, category, description, amount, account, note):
        """更新交易记录"""
        self.execute_update(
            "UPDATE transactions SET date=?, type=?, category=?, description=?, amount=?, account=?, note=? WHERE id=?",
            (date, type_, category, description, amount, account, note, id)
        )
    
    def delete_transaction(self, id):
        """删除交易记录"""
        self.execute_update("DELETE FROM transactions WHERE id=?", (id,))
    
    def add_category(self, name):
        """添加新分类"""
        self.execute_update("INSERT OR IGNORE INTO categories (name) VALUES (?)", (name,))
    
    def delete_category(self, name):
        """删除分类"""
        self.execute_update("DELETE FROM categories WHERE name=?", (name,))
    
    def add_account(self, name):
        """添加新账户"""
        self.execute_update("INSERT OR IGNORE INTO accounts (name) VALUES (?)", (name,))
    
    def delete_account(self, name):
        """删除账户"""
        self.execute_update("DELETE FROM accounts WHERE name=?", (name,))

class FinanceManagerApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("本地记账工具 v1.6")
        self.setGeometry(100, 100, 1200, 800)
        
        # 初始化数据库
        self.db = DatabaseManager()
        
        # 加载数据
        self.transactions = self.db.get_transactions()
        self.categories = self.db.get_categories()
        self.accounts = self.db.get_accounts()
        
        # 主题列表
        self.themes = {
            "默认主题": self.default_theme,
            "深色主题": self.dark_theme,
            "蓝色主题": self.blue_theme,
            "绿色主题": self.green_theme
        }
        
        # 创建主部件
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        
        # 主布局
        main_layout = QVBoxLayout()
        main_layout.setSpacing(15)
        main_layout.setContentsMargins(15, 15, 15, 15)
        self.central_widget.setLayout(main_layout)
        
        # 添加记录区域
        add_record_group = QGroupBox("添加新记录")
        add_record_layout = self.create_add_record_area()
        add_record_group.setLayout(add_record_layout)
        main_layout.addWidget(add_record_group)
        
        # 批量操作区域
        batch_actions_layout = self.create_batch_actions()
        main_layout.addLayout(batch_actions_layout)
        
        # 顶部工具栏
        filter_group = QGroupBox("筛选条件")
        filter_layout = self.create_top_toolbar()
        filter_group.setLayout(filter_layout)
        main_layout.addWidget(filter_group)
        
        # 创建标签页
        self.tab_widget = QTabWidget()
        self.tab_widget.setTabPosition(QTabWidget.North)
        
        # 表格视图
        self.table_view = self.create_table_view()
        self.tab_widget.addTab(self.table_view, "📝 交易记录")
        
        # 图表视图
        self.chart_tab = QWidget()
        self.setup_chart_tab()
        self.tab_widget.addTab(self.chart_tab, "📊 图表分析")
        
        # 分类管理
        self.category_tab = self.create_category_tab()
        self.tab_widget.addTab(self.category_tab, "🏷️ 分类管理")
        
        # 账户管理
        self.account_tab = self.create_account_tab()
        self.tab_widget.addTab(self.account_tab, "💳 账户管理")
        
        main_layout.addWidget(self.tab_widget, 1)
        
        # 状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.update_status_bar()
        
        # 创建菜单
        self.create_menus()
        
        # 应用默认主题
        self.apply_theme("默认主题")
        
        # 初始化表格数据
        self.update_table()
    
    def default_theme(self):
        """默认主题样式"""
        return """
            QMainWindow {
                background-color: #f5f7fa;
                font-family: "Microsoft YaHei";
                font-size: 14px;
            }
            QGroupBox {
                border: 1px solid #d1d5db;
                border-radius: 8px;
                margin-top: 1ex;
                font-weight: bold;
                padding: 10px;
                background: white;
                font-size: 14px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0 5px;
                font-size: 14px;
            }
            QTabWidget::pane {
                border: 1px solid #d1d5db;
                background: white;
                border-radius: 8px;
            }
            QTabBar::tab {
                background: #e5e7eb;
                border: 1px solid #d1d5db;
                padding: 8px 16px;
                border-top-left-radius: 8px;
                border-top-right-radius: 8px;
                margin-right: 2px;
                font-size: 14px;
            }
            QTabBar::tab:selected {
                background: white;
                border-bottom-color: white;
                font-weight: bold;
            }
            QTableWidget {
                background-color: white;
                alternate-background-color: #f9fafb;
                gridline-color: #e5e7eb;
                border-radius: 8px;
                font-size: 14px;
            }
            QHeaderView::section {
                background-color: #f3f4f6;
                padding: 8px;
                border: none;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton {
                background-color: #3b82f6;
                color: white;
                border-radius: 6px;
                padding: 8px 16px;
                font-weight: 500;
                font-size: 14px;
                min-height: 30px;
            }
            QPushButton:hover {
                background-color: #2563eb;
            }
            QPushButton:disabled {
                background-color: #9ca3af;
            }
            QPushButton#danger {
                background-color: #ef4444;
            }
            QPushButton#danger:hover {
                background-color: #dc2626;
            }
            QLineEdit, QComboBox, QDateEdit, QDoubleSpinBox {
                border: 1px solid #d1d5db;
                border-radius: 6px;
                padding: 8px;
                background: white;
                font-size: 14px;
                min-height: 30px;
            }
            QLineEdit:focus, QComboBox:focus, QDateEdit:focus, QDoubleSpinBox:focus {
                border: 1px solid #3b82f6;
            }
            QListWidget {
                border: 1px solid #d1d5db;
                border-radius: 8px;
                background: white;
                font-size: 14px;
            }
            QStatusBar {
                background-color: #f3f4f6;
                border-top: 1px solid #d1d5db;
                font-size: 14px;
            }
            QLabel {
                font-size: 14px;
            }
            QCheckBox {
                font-size: 14px;
            }
        """
    
    def dark_theme(self):
        """深色主题样式"""
        return """
            QMainWindow {
                background-color: #1e293b;
                color: #e2e8f0;
                font-family: "Microsoft YaHei";
                font-size: 14px;
            }
            QGroupBox {
                border: 1px solid #475569;
                border-radius: 8px;
                margin-top: 1ex;
                font-weight: bold;
                padding: 10px;
                background: #334155;
                color: #e2e8f0;
                font-size: 14px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0 5px;
                color: #e2e8f0;
                font-size: 14px;
            }
            QTabWidget::pane {
                border: 1px solid #475569;
                background: #334155;
                border-radius: 8px;
            }
            QTabBar::tab {
                background: #475569;
                border: 1px solid #475569;
                padding: 8px 16px;
                border-top-left-radius: 8px;
                border-top-right-radius: 8px;
                margin-right: 2px;
                color: #e2e8f0;
                font-size: 14px;
            }
            QTabBar::tab:selected {
                background: #334155;
                border-bottom-color: #334155;
                font-weight: bold;
            }
            QTableWidget {
                background-color: #334155;
                alternate-background-color: #3c4b64;
                gridline-color: #475569;
                border-radius: 8px;
                color: #e2e8f0;
                font-size: 14px;
            }
            QHeaderView::section {
                background-color: #475569;
                padding: 8px;
                border: none;
                font-weight: bold;
                color: #e2e8f0;
                font-size: 14px;
            }
            QPushButton {
                background-color: #3b82f6;
                color: white;
                border-radius: 6px;
                padding: 8px 16px;
                font-weight: 500;
                font-size: 14px;
                min-height: 30px;
            }
            QPushButton:hover {
                background-color: #2563eb;
            }
            QPushButton:disabled {
                background-color: #64748b;
            }
            QPushButton#danger {
                background-color: #ef4444;
            }
            QPushButton#danger:hover {
                background-color: #dc2626;
            }
            QLineEdit, QComboBox, QDateEdit, QDoubleSpinBox {
                border: 1px solid #475569;
                border-radius: 6px;
                padding: 8px;
                background: #475569;
                color: #e2e8f0;
                font-size: 14px;
                min-height: 30px;
            }
            QLineEdit:focus, QComboBox:focus, QDateEdit:focus, QDoubleSpinBox:focus {
                border: 1px solid #3b82f6;
            }
            QListWidget {
                border: 1px solid #475569;
                border-radius: 8px;
                background: #475569;
                color: #e2e8f0;
                font-size: 14px;
            }
            QStatusBar {
                background-color: #334155;
                border-top: 1px solid #475569;
                color: #e2e8f0;
                font-size: 14px;
            }
            QLabel {
                color: #e2e8f0;
                font-size: 14px;
            }
            QCheckBox {
                color: #e2e8f0;
                font-size: 14px;
            }
        """
    
    def blue_theme(self):
        """蓝色主题样式"""
        return """
            QMainWindow {
                background-color: #dbeafe;
                font-family: "Microsoft YaHei";
                font-size: 14px;
            }
            QGroupBox {
                border: 1px solid #93c5fd;
                border-radius: 8px;
                margin-top: 1ex;
                font-weight: bold;
                padding: 10px;
                background: white;
                font-size: 14px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0 5px;
                font-size: 14px;
            }
            QTabWidget::pane {
                border: 1px solid #93c5fd;
                background: white;
                border-radius: 8px;
            }
            QTabBar::tab {
                background: #dbeafe;
                border: 1px solid #93c5fd;
                padding: 8px 16px;
                border-top-left-radius: 8px;
                border-top-right-radius: 8px;
                margin-right: 2px;
                font-size: 14px;
            }
            QTabBar::tab:selected {
                background: white;
                border-bottom-color: white;
                font-weight: bold;
            }
            QTableWidget {
                background-color: white;
                alternate-background-color: #eff6ff;
                gridline-color: #dbeafe;
                border-radius: 8px;
                font-size: 14px;
            }
            QHeaderView::section {
                background-color: #dbeafe;
                padding: 8px;
                border: none;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton {
                background-color: #3b82f6;
                color: white;
                border-radius: 6px;
                padding: 8px 16px;
                font-weight: 500;
                font-size: 14px;
                min-height: 30px;
            }
            QPushButton:hover {
                background-color: #2563eb;
            }
            QPushButton:disabled {
                background-color: #9ca3af;
            }
            QPushButton#danger {
                background-color: #ef4444;
            }
            QPushButton#danger:hover {
                background-color: #dc2626;
            }
            QLineEdit, QComboBox, QDateEdit, QDoubleSpinBox {
                border: 1px solid #93c5fd;
                border-radius: 6px;
                padding: 8px;
                background: white;
                font-size: 14px;
                min-height: 30px;
            }
            QLineEdit:focus, QComboBox:focus, QDateEdit:focus, QDoubleSpinBox:focus {
                border: 1px solid #3b82f6;
            }
            QListWidget {
                border: 1px solid #93c5fd;
                border-radius: 8px;
                background: white;
                font-size: 14px;
            }
            QStatusBar {
                background-color: #dbeafe;
                border-top: 1px solid #93c5fd;
                font-size: 14px;
            }
            QLabel {
                font-size: 14px;
            }
            QCheckBox {
                font-size: 14px;
            }
        """
    
    def green_theme(self):
        """绿色主题样式"""
        return """
            QMainWindow {
                background-color: #dcfce7;
                font-family: "Microsoft YaHei";
                font-size: 14px;
            }
            QGroupBox {
                border: 1px solid #86efac;
                border-radius: 8px;
                margin-top: 1ex;
                font-weight: bold;
                padding: 10px;
                background: white;
                font-size: 14px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0 5px;
                font-size: 14px;
            }
            QTabWidget::pane {
                border: 1px solid #86efac;
                background: white;
                border-radius: 8px;
            }
            QTabBar::tab {
                background: #dcfce7;
                border: 1px solid #86efac;
                padding: 8px 16px;
                border-top-left-radius: 8px;
                border-top-right-radius: 8px;
                margin-right: 2px;
                font-size: 14px;
            }
            QTabBar::tab:selected {
                background: white;
                border-bottom-color: white;
                font-weight: bold;
            }
            QTableWidget {
                background-color: white;
                alternate-background-color: #f0fdf4;
                gridline-color: #dcfce7;
                border-radius: 8px;
                font-size: 14px;
            }
            QHeaderView::section {
                background-color: #dcfce7;
                padding: 8px;
                border: none;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton {
                background-color: #22c55e;
                color: white;
                border-radius: 6px;
                padding: 8px 16px;
                font-weight: 500;
                font-size: 14px;
                min-height: 30px;
            }
            QPushButton:hover {
                background-color: #16a34a;
            }
            QPushButton:disabled {
                background-color: #9ca3af;
            }
            QPushButton#danger {
                background-color: #ef4444;
            }
            QPushButton#danger:hover {
                background-color: #dc2626;
            }
            QLineEdit, QComboBox, QDateEdit, QDoubleSpinBox {
                border: 1px solid #86efac;
                border-radius: 6px;
                padding: 8px;
                background: white;
                font-size: 14px;
                min-height: 30px;
            }
            QLineEdit:focus, QComboBox:focus, QDateEdit:focus, QDoubleSpinBox:focus {
                border: 1px solid #22c55e;
            }
            QListWidget {
                border: 1px solid #86efac;
                border-radius: 8px;
                background: white;
                font-size: 14px;
            }
            QStatusBar {
                background-color: #dcfce7;
                border-top: 1px solid #86efac;
                font-size: 14px;
            }
            QLabel {
                font-size: 14px;
            }
            QCheckBox {
                font-size: 14px;
            }
        """
    
    def apply_theme(self, theme_name):
        """应用选定的主题"""
        if theme_name in self.themes:
            self.setStyleSheet(self.themes[theme_name]())
    
    def create_batch_actions(self):
        """创建批量操作区域"""
        layout = QHBoxLayout()
        layout.setSpacing(10)
        
        # 全选按钮
        self.select_all_button = QPushButton("全选")
        self.select_all_button.setStyleSheet("background-color: #e0e7ff; color: #1e40af;")
        self.select_all_button.clicked.connect(self.select_all_records)
        layout.addWidget(self.select_all_button)
        
        # 取消全选按钮
        self.deselect_all_button = QPushButton("取消全选")
        self.deselect_all_button.setStyleSheet("background-color: #e0e7ff; color: #1e40af;")
        self.deselect_all_button.clicked.connect(self.deselect_all_records)
        layout.addWidget(self.deselect_all_button)
        
        # 批量删除按钮
        self.batch_delete_button = QPushButton("批量删除")
        self.batch_delete_button.setObjectName("danger")
        self.batch_delete_button.clicked.connect(self.batch_delete_records)
        layout.addWidget(self.batch_delete_button)
        
        # 添加弹性空间
        layout.addStretch()
        
        return layout
    
    def create_add_record_area(self):
        """创建添加记录的区域"""
        layout = QHBoxLayout()
        layout.setSpacing(15)
        
        # 日期输入
        self.date_input = QDateEdit(QDate.currentDate())
        self.date_input.setCalendarPopup(True)
        self.date_input.setDisplayFormat("yyyy-MM-dd")
        layout.addWidget(QLabel("日期:"))
        layout.addWidget(self.date_input)
        
        # 类型选择
        self.type_combo = QComboBox()
        self.type_combo.addItems(["支出", "收入"])
        layout.addWidget(QLabel("类型:"))
        layout.addWidget(self.type_combo)
        
        # 分类选择
        self.category_combo = QComboBox()
        self.category_combo.addItems(self.categories)
        layout.addWidget(QLabel("分类:"))
        layout.addWidget(self.category_combo)
        
        # 描述输入
        self.desc_input = QLineEdit()
        self.desc_input.setPlaceholderText("交易描述")
        layout.addWidget(QLabel("描述:"))
        layout.addWidget(self.desc_input)
        
        # 金额输入
        self.amount_input = QDoubleSpinBox()
        self.amount_input.setRange(0, 100000)
        self.amount_input.setPrefix("￥")
        self.amount_input.setDecimals(2)
        layout.addWidget(QLabel("金额:"))
        layout.addWidget(self.amount_input)
        
        # 账户选择
        self.account_combo = QComboBox()
        self.account_combo.addItems(self.accounts)
        layout.addWidget(QLabel("账户:"))
        layout.addWidget(self.account_combo)
        
        # 保存按钮
        self.save_button = QPushButton("💾 保存记录")
        self.save_button.setStyleSheet("background-color: #2e7d32; color: white;")
        self.save_button.clicked.connect(self.save_new_record)
        layout.addWidget(self.save_button)
        
        return layout
    
    def create_top_toolbar(self):
        toolbar_layout = QHBoxLayout()
        toolbar_layout.setSpacing(15)
        
        # 类型选择器
        self.filter_type_combo = QComboBox()
        self.filter_type_combo.addItems(["所有类型", "收入", "支出"])
        self.filter_type_combo.setCurrentText("所有类型")
        self.filter_type_combo.currentIndexChanged.connect(self.update_table)
        toolbar_layout.addWidget(QLabel("类型筛选:"))
        toolbar_layout.addWidget(self.filter_type_combo)
        
        # 账户选择器
        self.filter_account_combo = QComboBox()
        self.filter_account_combo.addItems(["所有账户"] + self.accounts)
        self.filter_account_combo.setCurrentText("所有账户")
        self.filter_account_combo.currentIndexChanged.connect(self.update_table)
        toolbar_layout.addWidget(QLabel("账户筛选:"))
        toolbar_layout.addWidget(self.filter_account_combo)
        
        # 搜索框
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("搜索描述、备注...")
        self.search_input.textChanged.connect(self.update_table)
        toolbar_layout.addWidget(QLabel("搜索:"))
        toolbar_layout.addWidget(self.search_input)
        
        # 添加弹性空间使按钮在右侧
        toolbar_layout.addStretch()
        
        return toolbar_layout
    
    def create_table_view(self):
        table = QTableWidget()
        # 列数调整：移除了标签列
        table.setColumnCount(10)  # 序号、选择框、日期、类型、分类、描述、金额、账户、备注、操作
        table.setHorizontalHeaderLabels([
            "#", "选择", "日期", "类型", "分类", "描述", "金额", "账户", "备注", "操作"
        ])
        
        table.setSelectionBehavior(QAbstractItemView.SelectRows)
        table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        table.verticalHeader().setVisible(False)
        table.setSortingEnabled(True)
        table.setAlternatingRowColors(True)
        
        # 设置表头拉伸
        header = table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeToContents)  # 序号
        header.setSectionResizeMode(1, QHeaderView.ResizeToContents)  # 选择框
        header.setSectionResizeMode(2, QHeaderView.ResizeToContents)  # 日期
        header.setSectionResizeMode(3, QHeaderView.ResizeToContents)  # 类型
        header.setSectionResizeMode(4, QHeaderView.ResizeToContents)  # 分类
        header.setSectionResizeMode(5, QHeaderView.Stretch)           # 描述
        header.setSectionResizeMode(6, QHeaderView.ResizeToContents)  # 金额
        header.setSectionResizeMode(7, QHeaderView.ResizeToContents)  # 账户
        header.setSectionResizeMode(8, QHeaderView.Stretch)           # 备注
        header.setSectionResizeMode(9, QHeaderView.ResizeToContents)  # 操作
        
        # 设置行高
        table.verticalHeader().setDefaultSectionSize(40)
        
        return table
    
    def setup_chart_tab(self):
        layout = QVBoxLayout()
        layout.setSpacing(15)
        
        # 创建图表选择按钮
        chart_buttons_layout = QHBoxLayout()
        chart_buttons_layout.setSpacing(10)
        
        expense_button = QPushButton("📉 支出分类")
        expense_button.setStyleSheet("background-color: #fef3c7; color: #92400e;")
        expense_button.clicked.connect(self.show_expense_chart)
        chart_buttons_layout.addWidget(expense_button)
        
        income_button = QPushButton("📈 收入分类")
        income_button.setStyleSheet("background-color: #dcfce7; color: #166534;")
        income_button.clicked.connect(self.show_income_chart)
        chart_buttons_layout.addWidget(income_button)
        
        trend_button = QPushButton("📊 月度趋势")
        trend_button.setStyleSheet("background-color: #dbeafe; color: #1e40af;")
        trend_button.clicked.connect(self.show_monthly_trend)
        chart_buttons_layout.addWidget(trend_button)
        
        account_button = QPushButton("💳 账户分布")
        account_button.setStyleSheet("background-color: #ede9fe; color: #5b21b6;")
        account_button.clicked.connect(self.show_account_chart)
        chart_buttons_layout.addWidget(account_button)
        
        layout.addLayout(chart_buttons_layout)
        
        # 图表容器
        self.figure = Figure(facecolor='#f9fafb')
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setStyleSheet("background-color: white; border-radius: 8px;")
        layout.addWidget(self.canvas, 1)
        
        self.chart_tab.setLayout(layout)
    
    def create_category_tab(self):
        tab = QWidget()
        layout = QVBoxLayout()
        layout.setSpacing(15)
        
        # 分类列表
        self.category_list = QListWidget()
        self.category_list.addItems(self.categories)
        layout.addWidget(self.category_list, 1)
        
        # 操作按钮
        buttons_layout = QHBoxLayout()
        buttons_layout.setSpacing(10)
        
        add_button = QPushButton("➕ 添加分类")
        add_button.clicked.connect(self.add_category)
        buttons_layout.addWidget(add_button)
        
        edit_button = QPushButton("✏️ 重命名")
        edit_button.clicked.connect(self.edit_category)
        buttons_layout.addWidget(edit_button)
        
        remove_button = QPushButton("🗑️ 删除分类")
        remove_button.setObjectName("danger")
        remove_button.clicked.connect(self.remove_category)
        buttons_layout.addWidget(remove_button)
        
        layout.addLayout(buttons_layout)
        
        tab.setLayout(layout)
        return tab
    
    def create_account_tab(self):
        tab = QWidget()
        layout = QVBoxLayout()
        layout.setSpacing(15)
        
        # 账户列表
        self.account_list = QListWidget()
        self.account_list.addItems(self.accounts)
        layout.addWidget(self.account_list, 1)
        
        # 操作按钮
        buttons_layout = QHBoxLayout()
        buttons_layout.setSpacing(10)
        
        add_button = QPushButton("➕ 添加账户")
        add_button.clicked.connect(self.add_account)
        buttons_layout.addWidget(add_button)
        
        edit_button = QPushButton("✏️ 重命名")
        edit_button.clicked.connect(self.edit_account)
        buttons_layout.addWidget(edit_button)
        
        remove_button = QPushButton("🗑️ 删除账户")
        remove_button.setObjectName("danger")
        remove_button.clicked.connect(self.remove_account)
        buttons_layout.addWidget(remove_button)
        
        layout.addLayout(buttons_layout)
        
        tab.setLayout(layout)
        return tab
    
    def create_menus(self):
        # 文件菜单
        file_menu = self.menuBar().addMenu("文件")
        
        export_action = QAction("📤 导出CSV", self)
        export_action.triggered.connect(self.export_to_csv)
        file_menu.addAction(export_action)
        
        import_action = QAction("📥 导入CSV", self)
        import_action.triggered.connect(self.import_from_csv)
        file_menu.addAction(import_action)
        
        file_menu.addSeparator()
        
        exit_action = QAction("🚪 退出", self)
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 主题菜单
        theme_menu = self.menuBar().addMenu("主题")
        
        for theme_name in self.themes.keys():
            action = QAction(theme_name, self)
            action.triggered.connect(lambda checked, name=theme_name: self.apply_theme(name))
            theme_menu.addAction(action)
        
        # 帮助菜单
        help_menu = self.menuBar().addMenu("帮助")
        
        about_action = QAction("ℹ️ 关于", self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)
    
    def update_table(self):
        """更新表格数据"""
        # 从数据库重新加载所有数据
        self.transactions = self.db.get_transactions()
        
        # 应用筛选条件
        filtered_data = self.transactions.copy()
        
        # 应用类型筛选
        if self.filter_type_combo.currentText() != "所有类型":
            type_filter = self.filter_type_combo.currentText()
            filtered_data = [t for t in filtered_data if t[2] == type_filter]  # type在索引2
        
        # 应用账户筛选
        if self.filter_account_combo.currentText() != "所有账户":
            account_filter = self.filter_account_combo.currentText()
            filtered_data = [t for t in filtered_data if t[6] == account_filter]  # account在索引6
        
        # 应用搜索筛选
        search_text = self.search_input.text().lower()
        if search_text:
            filtered_data = [t for t in filtered_data if 
                            (search_text in t[4].lower()) or  # description在索引4
                            (search_text in t[7].lower())]    # note在索引7
        
        # 更新表格
        self.table_view.setRowCount(len(filtered_data))
        
        for row_idx, record in enumerate(filtered_data):
            # 序号列 - 显示行号（从1开始）
            self.table_view.setItem(row_idx, 0, QTableWidgetItem(str(row_idx + 1)))
            
            # 选择框列
            checkbox = QCheckBox()
            checkbox.setProperty("record_id", record[0])
            checkbox_widget = QWidget()
            checkbox_layout = QHBoxLayout(checkbox_widget)
            checkbox_layout.addWidget(checkbox)
            checkbox_layout.setAlignment(Qt.AlignCenter)
            checkbox_layout.setContentsMargins(0, 0, 0, 0)
            self.table_view.setCellWidget(row_idx, 1, checkbox_widget)
            
            # 日期列
            date_item = QTableWidgetItem(record[1])  # date在索引1
            date_item.setTextAlignment(Qt.AlignCenter)
            self.table_view.setItem(row_idx, 2, date_item)
            
            # 类型列
            type_item = QTableWidgetItem(record[2])  # type在索引2
            type_item.setTextAlignment(Qt.AlignCenter)
            if record[2] == "收入":
                type_item.setForeground(QColor("#166534"))  # 深绿色
            else:
                type_item.setForeground(QColor("#b91c1c"))  # 深红色
            self.table_view.setItem(row_idx, 3, type_item)
            
            # 分类列
            category_item = QTableWidgetItem(record[3])  # category在索引3
            category_item.setTextAlignment(Qt.AlignCenter)
            self.table_view.setItem(row_idx, 4, category_item)
            
            # 描述列
            self.table_view.setItem(row_idx, 5, QTableWidgetItem(record[4]))  # description在索引4
            
            # 金额列
            amount_item = QTableWidgetItem(f"￥{record[5]:.2f}")  # amount在索引5
            amount_item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
            if record[2] == "收入":
                amount_item.setForeground(QColor("#166534"))  # 深绿色
            else:
                amount_item.setForeground(QColor("#b91c1c"))  # 深红色
            self.table_view.setItem(row_idx, 6, amount_item)
            
            # 账户列
            account_item = QTableWidgetItem(record[6])  # account在索引6
            account_item.setTextAlignment(Qt.AlignCenter)
            self.table_view.setItem(row_idx, 7, account_item)
            
            # 备注列
            note_value = record[7]  # note在索引7
            if not isinstance(note_value, str):
                note_value = str(note_value)
            self.table_view.setItem(row_idx, 8, QTableWidgetItem(note_value))
            
            # 操作列
            edit_button = QPushButton("✏️ 编辑")
            edit_button.setStyleSheet("background-color: #f0f9ff; color: #0369a1;")
            edit_button.setProperty("record_id", record[0])
            edit_button.clicked.connect(self.edit_record)
            
            delete_button = QPushButton("🗑️ 删除")
            delete_button.setObjectName("danger")
            delete_button.setProperty("record_id", record[0])
            delete_button.clicked.connect(self.delete_record)
            
            button_layout = QHBoxLayout()
            button_layout.addWidget(edit_button)
            button_layout.addWidget(delete_button)
            button_layout.setContentsMargins(0, 0, 0, 0)
            button_layout.setSpacing(5)
            
            button_widget = QWidget()
            button_widget.setLayout(button_layout)
            
            self.table_view.setCellWidget(row_idx, 9, button_widget)
        
        # 更新状态栏
        self.update_status_bar()
    
    def update_status_bar(self):
        """更新状态栏统计信息"""
        # 计算统计信息
        income = sum(t[5] for t in self.transactions if t[2] == "收入")
        expenses = sum(t[5] for t in self.transactions if t[2] == "支出")
        balance = income - expenses
        
        # 更新状态栏
        self.status_bar.showMessage(
            f"总收入: ￥{income:,.2f} | "
            f"总支出: ￥{expenses:,.2f} | "
            f"余额: ￥{balance:,.2f}"
        )
    
    def save_new_record(self):
        """保存新记录"""
        # 验证输入
        if not self.desc_input.text().strip():
            QMessageBox.warning(self, "输入错误", "描述不能为空")
            return
        
        # 添加新记录到数据库
        new_id = self.db.add_transaction(
            date=self.date_input.date().toString("yyyy-MM-dd"),
            type_=self.type_combo.currentText(),
            category=self.category_combo.currentText(),
            description=self.desc_input.text(),
            amount=self.amount_input.value(),
            account=self.account_combo.currentText()
        )
        
        if new_id:
            # 清空输入框
            self.desc_input.clear()
            self.amount_input.setValue(0)
            
            # 更新表格
            self.update_table()
            
            QMessageBox.information(self, "成功", "记录已添加")
        else:
            QMessageBox.warning(self, "错误", "添加记录失败")
    
    def edit_record(self):
        """编辑记录"""
        button = self.sender()
        record_id = button.property("record_id")
        
        # 查找记录
        record = next((t for t in self.transactions if t[0] == record_id), None)
        if not record:
            QMessageBox.warning(self, "错误", "找不到记录")
            return
        
        # 创建编辑对话框
        dialog = QDialog(self)
        dialog.setWindowTitle("编辑记录")
        dialog.setGeometry(300, 300, 500, 400)
        
        layout = QFormLayout()
        layout.setSpacing(15)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 日期输入
        date_input = QDateEdit(QDate.fromString(record[1], "yyyy-MM-dd"))
        date_input.setCalendarPopup(True)
        date_input.setDisplayFormat("yyyy-MM-dd")
        layout.addRow("日期:", date_input)
        
        # 类型选择
        type_combo = QComboBox()
        type_combo.addItems(["支出", "收入"])
        type_combo.setCurrentText(record[2])
        layout.addRow("类型:", type_combo)
        
        # 分类选择
        category_combo = QComboBox()
        category_combo.addItems(self.categories)
        category_combo.setCurrentText(record[3])
        layout.addRow("分类:", category_combo)
        
        # 描述输入
        desc_input = QLineEdit(record[4])
        layout.addRow("描述:", desc_input)
        
        # 金额输入
        amount_input = QDoubleSpinBox()
        amount_input.setRange(0, 100000)
        amount_input.setPrefix("￥")
        amount_input.setDecimals(2)
        amount_input.setValue(record[5])
        layout.addRow("金额:", amount_input)
        
        # 账户选择
        account_combo = QComboBox()
        account_combo.addItems(self.accounts)
        account_combo.setCurrentText(record[6])
        layout.addRow("账户:", account_combo)
        
        # 备注输入
        note_input = QLineEdit(record[7])
        layout.addRow("备注:", note_input)
        
        # 按钮
        button_box = QHBoxLayout()
        save_button = QPushButton("💾 保存")
        cancel_button = QPushButton("❌ 取消")
        
        def save_changes():
            # 更新数据库记录
            self.db.update_transaction(
                id=record_id,
                date=date_input.date().toString("yyyy-MM-dd"),
                type_=type_combo.currentText(),
                category=category_combo.currentText(),
                description=desc_input.text(),
                amount=amount_input.value(),
                account=account_combo.currentText(),
                note=note_input.text()
            )
            
            # 更新表格
            self.update_table()
            
            dialog.accept()
            QMessageBox.information(self, "成功", "记录已更新")
        
        save_button.clicked.connect(save_changes)
        cancel_button.clicked.connect(dialog.reject)
        
        button_box.addStretch()
        button_box.addWidget(save_button)
        button_box.addWidget(cancel_button)
        layout.addRow(button_box)
        
        dialog.setLayout(layout)
        dialog.exec_()
    
    def delete_record(self):
        """删除记录"""
        button = self.sender()
        record_id = button.property("record_id")
        
        # 确认删除
        reply = QMessageBox.question(
            self, "确认删除", 
            f"确定要删除记录 #{record_id} 吗?",
            QMessageBox.Yes | QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            # 从数据库删除记录
            self.db.delete_transaction(record_id)
            
            # 更新表格
            self.update_table()
            
            QMessageBox.information(self, "成功", "记录已删除")
    
    def select_all_records(self):
        """全选记录"""
        for row in range(self.table_view.rowCount()):
            checkbox_widget = self.table_view.cellWidget(row, 1)
            checkbox = checkbox_widget.findChild(QCheckBox)
            if checkbox:
                checkbox.setChecked(True)
    
    def deselect_all_records(self):
        """取消全选记录"""
        for row in range(self.table_view.rowCount()):
            checkbox_widget = self.table_view.cellWidget(row, 1)
            checkbox = checkbox_widget.findChild(QCheckBox)
            if checkbox:
                checkbox.setChecked(False)
    
    def batch_delete_records(self):
        """批量删除选中的记录"""
        # 获取选中的记录ID
        selected_ids = []
        for row in range(self.table_view.rowCount()):
            checkbox_widget = self.table_view.cellWidget(row, 1)
            checkbox = checkbox_widget.findChild(QCheckBox)
            if checkbox and checkbox.isChecked():
                # 获取记录ID（从数据库记录中获取）
                record_id = self.table_view.item(row, 0).data(Qt.UserRole)
                if not record_id:
                    # 如果没有设置UserRole，尝试从操作按钮获取
                    button_widget = self.table_view.cellWidget(row, 9)
                    if button_widget:
                        buttons = button_widget.findChildren(QPushButton)
                        if buttons:
                            record_id = buttons[0].property("record_id")
                
                if record_id:
                    selected_ids.append(record_id)
        
        if not selected_ids:
            QMessageBox.warning(self, "警告", "请先选择要删除的记录")
            return
        
        # 确认删除
        reply = QMessageBox.question(
            self, "确认批量删除", 
            f"确定要删除选中的 {len(selected_ids)} 条记录吗?",
            QMessageBox.Yes | QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            # 批量删除记录
            for record_id in selected_ids:
                self.db.delete_transaction(record_id)
            
            # 更新表格
            self.update_table()
            
            QMessageBox.information(self, "成功", f"已删除 {len(selected_ids)} 条记录")
    
    def export_to_csv(self):
        file_path, _ = QFileDialog.getSaveFileName(
            self, "导出CSV文件", "", "CSV文件 (*.csv)"
        )
        
        if file_path:
            # 从数据库获取所有记录
            records = self.db.get_transactions()
            
            # 转换为DataFrame
            df = pd.DataFrame(records, columns=[
                "id", "date", "type", "category", "description", "amount", "account", "note"
            ])
            
            # 导出到CSV
            df.to_csv(file_path, index=False)
            QMessageBox.information(self, "导出成功", f"数据已成功导出到: {file_path}")
    
    def import_from_csv(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self, "导入CSV文件", "", "CSV文件 (*.csv)"
        )
        
        if file_path:
            try:
                # 读取CSV文件
                df = pd.read_csv(file_path)
                
                # 确保有必要的列
                required_columns = ["date", "type", "category", "description", "amount", "account"]
                if not all(col in df.columns for col in required_columns):
                    QMessageBox.warning(self, "导入失败", "CSV文件中缺少必需的列")
                    return
                
                # 添加缺失的列
                if "note" not in df.columns:
                    df["note"] = ""
                
                # 导入到数据库
                for _, row in df.iterrows():
                    self.db.add_transaction(
                        date=row["date"],
                        type_=row["type"],
                        category=row["category"],
                        description=row["description"],
                        amount=row["amount"],
                        account=row["account"],
                        note=row.get("note", "")
                    )
                
                # 更新表格
                self.update_table()
                
                QMessageBox.information(self, "导入成功", f"成功导入 {len(df)} 条记录")
            except Exception as e:
                QMessageBox.warning(self, "导入失败", f"导入CSV文件时出错: {str(e)}")
    
    def show_expense_chart(self):
        # 过滤支出数据
        expense_data = [t for t in self.transactions if t[2] == "支出"]
        
        if not expense_data:
            QMessageBox.warning(self, "无数据", "没有支出记录可展示")
            return
        
        # 按分类汇总支出
        category_expenses = {}
        for record in expense_data:
            category = record[3]
            amount = record[5]
            category_expenses[category] = category_expenses.get(category, 0) + amount
        
        # 创建饼图
        self.figure.clear()
        ax = self.figure.add_subplot(111)
        ax.set_facecolor('#f9fafb')
        
        if category_expenses:
            categories = list(category_expenses.keys())
            amounts = list(category_expenses.values())
            
            # 使用更鲜艳的颜色
            colors = plt.cm.Pastel1(range(len(categories)))
            
            # 创建饼图
            wedges, texts, autotexts = ax.pie(
                amounts, 
                labels=categories,
                autopct='%1.1f%%',
                startangle=90,
                colors=colors,
                wedgeprops={'edgecolor': 'w', 'linewidth': 1}
            )
            
            # 设置字体大小
            for text in texts + autotexts:
                text.set_fontsize(10)
            
            ax.set_title("支出分类占比", fontsize=14, fontweight='bold')
            ax.axis('equal')  # 确保饼图是圆的
            
            # 添加图例
            ax.legend(wedges, categories, 
                      title="分类",
                      loc="center left",
                      bbox_to_anchor=(1, 0, 0.5, 1))
        else:
            ax.text(0.5, 0.5, '没有支出数据', ha='center', va='center', fontsize=12)
        
        self.canvas.draw()
    
    def show_income_chart(self):
        # 过滤收入数据
        income_data = [t for t in self.transactions if t[2] == "收入"]
        
        if not income_data:
            QMessageBox.warning(self, "无数据", "没有收入记录可展示")
            return
        
        # 按分类汇总收入
        category_income = {}
        for record in income_data:
            category = record[3]
            amount = record[5]
            category_income[category] = category_income.get(category, 0) + amount
        
        # 创建饼图
        self.figure.clear()
        ax = self.figure.add_subplot(111)
        ax.set_facecolor('#f9fafb')
        
        if category_income:
            categories = list(category_income.keys())
            amounts = list(category_income.values())
            
            # 使用更鲜艳的颜色
            colors = plt.cm.Pastel2(range(len(categories)))
            
            # 创建饼图
            wedges, texts, autotexts = ax.pie(
                amounts, 
                labels=categories,
                autopct='%1.1f%%',
                startangle=90,
                colors=colors,
                wedgeprops={'edgecolor': 'w', 'linewidth': 1}
            )
            
            # 设置字体大小
            for text in texts + autotexts:
                text.set_fontsize(10)
            
            ax.set_title("收入分类占比", fontsize=14, fontweight='bold')
            ax.axis('equal')  # 确保饼图是圆的
            
            # 添加图例
            ax.legend(wedges, categories, 
                      title="分类",
                      loc="center left",
                      bbox_to_anchor=(1, 0, 0.5, 1))
        else:
            ax.text(0.5, 0.5, '没有收入数据', ha='center', va='center', fontsize=12)
        
        self.canvas.draw()
    
    def show_monthly_trend(self):
        # 处理日期列
        data = self.transactions.copy()
        
        # 提取月份
        monthly_data = {}
        for record in data:
            # 提取月份（格式：2025-07）
            month = record[1][:7]
            if month not in monthly_data:
                monthly_data[month] = {"收入": 0, "支出": 0}
            
            if record[2] == "收入":
                monthly_data[month]["收入"] += record[5]
            else:
                monthly_data[month]["支出"] += record[5]
        
        # 转换为DataFrame
        months = sorted(monthly_data.keys())
        income = [monthly_data[m]["收入"] for m in months]
        expense = [monthly_data[m]["支出"] for m in months]
        
        # 创建柱状图
        self.figure.clear()
        ax = self.figure.add_subplot(111)
        ax.set_facecolor('#f9fafb')
        
        if monthly_data:
            x = range(len(months))
            width = 0.35
            
            # 创建柱状图
            rects1 = ax.bar(x, income, width, label='收入', color='#86efac')
            rects2 = ax.bar([p + width for p in x], expense, width, label='支出', color='#fca5a5')
            
            # 添加数值标签
            def autolabel(rects):
                for rect in rects:
                    height = rect.get_height()
                    if height > 0:
                        ax.annotate(f'{height:.0f}',
                                    xy=(rect.get_x() + rect.get_width() / 2, height),
                                    xytext=(0, 3),  # 3 points vertical offset
                                    textcoords="offset points",
                                    ha='center', va='bottom', fontsize=8)
            
            autolabel(rects1)
            autolabel(rects2)
            
            # 设置标题和标签
            ax.set_title("月度收支趋势", fontsize=14, fontweight='bold')
            ax.set_xlabel("月份", fontsize=10)
            ax.set_ylabel("金额", fontsize=10)
            ax.set_xticks([p + width/2 for p in x])
            ax.set_xticklabels(months, rotation=45, ha='right', fontsize=9)
            ax.legend(fontsize=10)
            ax.grid(True, linestyle='--', alpha=0.7)
            
            # 调整布局
            plt.tight_layout()
        else:
            ax.text(0.5, 0.5, '没有足够的月度数据', ha='center', va='center', fontsize=12)
        
        self.canvas.draw()
    
    def show_account_chart(self):
        # 计算账户余额
        account_balance = {}
        for record in self.transactions:
            account = record[6]
            if account not in account_balance:
                account_balance[account] = 0
            
            if record[2] == "收入":
                account_balance[account] += record[5]
            else:
                account_balance[account] -= record[5]
        
        # 创建条形图
        self.figure.clear()
        ax = self.figure.add_subplot(111)
        ax.set_facecolor('#f9fafb')
        
        if account_balance:
            accounts = list(account_balance.keys())
            balances = list(account_balance.values())
            
            # 为正值和负值设置不同颜色
            colors = ['#86efac' if b >= 0 else '#fca5a5' for b in balances]
            
            # 创建条形图
            bars = ax.barh(accounts, balances, color=colors, edgecolor='white')
            
            # 添加数值标签
            for bar in bars:
                width = bar.get_width()
                label_x = width if width >= 0 else width
                ax.text(label_x, bar.get_y() + bar.get_height()/2,
                        f'￥{width:.2f}',
                        va='center', ha='right' if width < 0 else 'left',
                        fontsize=9)
            
            # 设置标题和标签
            ax.set_title("账户余额分布", fontsize=14, fontweight='bold')
            ax.set_xlabel("余额", fontsize=10)
            ax.grid(True, axis='x', linestyle='--', alpha=0.7)
            
            # 调整布局
            plt.tight_layout()
        else:
            ax.text(0.5, 0.5, '没有账户数据', ha='center', va='center', fontsize=12)
        
        self.canvas.draw()
    
    def add_category(self):
        name, ok = QInputDialog.getText(
            self, "添加新分类", "请输入分类名称:"
        )
        
        if ok and name:
            # 添加到数据库
            self.db.add_category(name)
            
            # 更新本地数据
            self.categories = self.db.get_categories()
            
            # 更新UI
            self.category_list.clear()
            self.category_list.addItems(self.categories)
            self.category_combo.clear()
            self.category_combo.addItems(self.categories)
            
            QMessageBox.information(self, "成功", f"分类 '{name}' 已添加")
    
    def edit_category(self):
        selected_items = self.category_list.selectedItems()
        
        if not selected_items:
            QMessageBox.warning(self, "警告", "请先选择一个分类")
            return
            
        current_name = selected_items[0].text()
        new_name, ok = QInputDialog.getText(
            self, "重命名分类", "请输入新名称:", text=current_name
        )
        
        if ok and new_name and new_name != current_name:
            # 更新数据库中的分类名称
            self.db.execute_update("""
            UPDATE transactions 
            SET category = ? 
            WHERE category = ?
            """, (new_name, current_name))
            
            # 删除旧分类
            self.db.delete_category(current_name)
            
            # 添加新分类
            self.db.add_category(new_name)
            
            # 更新本地数据
            self.categories = self.db.get_categories()
            
            # 更新UI
            self.category_list.clear()
            self.category_list.addItems(self.categories)
            self.category_combo.clear()
            self.category_combo.addItems(self.categories)
            
            # 更新表格
            self.update_table()
            
            QMessageBox.information(self, "成功", f"分类已重命名为 '{new_name}'")
    
    def remove_category(self):
        selected_items = self.category_list.selectedItems()
        
        if not selected_items:
            QMessageBox.warning(self, "警告", "请先选择一个分类")
            return
            
        name = selected_items[0].text()
        
        # 检查该分类是否被使用
        self.db.cursor.execute("SELECT COUNT(*) FROM transactions WHERE category=?", (name,))
        count = self.db.cursor.fetchone()[0]
        if count > 0:
            QMessageBox.warning(
                self, "无法删除", 
                f"分类 '{name}' 已被使用，请先修改相关记录"
            )
            return
            
        reply = QMessageBox.question(
            self, "确认删除", 
            f"确定要删除分类 '{name}' 吗?",
            QMessageBox.Yes | QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            # 从数据库删除分类
            self.db.delete_category(name)
            
            # 更新本地数据
            self.categories = self.db.get_categories()
            
            # 更新UI
            self.category_list.clear()
            self.category_list.addItems(self.categories)
            
            QMessageBox.information(self, "成功", f"分类 '{name}' 已删除")
    
    def add_account(self):
        name, ok = QInputDialog.getText(
            self, "添加新账户", "请输入账户名称:"
        )
        
        if ok and name:
            # 添加到数据库
            self.db.add_account(name)
            
            # 更新本地数据
            self.accounts = self.db.get_accounts()
            
            # 更新UI
            self.account_list.clear()
            self.account_list.addItems(self.accounts)
            self.account_combo.clear()
            self.account_combo.addItems(self.accounts)
            self.filter_account_combo.clear()
            self.filter_account_combo.addItems(["所有账户"] + self.accounts)
            
            QMessageBox.information(self, "成功", f"账户 '{name}' 已添加")
    
    def edit_account(self):
        selected_items = self.account_list.selectedItems()
        
        if not selected_items:
            QMessageBox.warning(self, "警告", "请先选择一个账户")
            return
            
        current_name = selected_items[0].text()
        new_name, ok = QInputDialog.getText(
            self, "重命名账户", "请输入新名称:", text=current_name
        )
        
        if ok and new_name and new_name != current_name:
            # 更新数据库中的账户名称
            self.db.execute_update("""
            UPDATE transactions 
            SET account = ? 
            WHERE account = ?
            """, (new_name, current_name))
            
            # 删除旧账户
            self.db.delete_account(current_name)
            
            # 添加新账户
            self.db.add_account(new_name)
            
            # 更新本地数据
            self.accounts = self.db.get_accounts()
            
            # 更新UI
            self.account_list.clear()
            self.account_list.addItems(self.accounts)
            self.account_combo.clear()
            self.account_combo.addItems(self.accounts)
            self.filter_account_combo.clear()
            self.filter_account_combo.addItems(["所有账户"] + self.accounts)
            
            # 更新表格
            self.update_table()
            
            QMessageBox.information(self, "成功", f"账户已重命名为 '{new_name}'")
    
    def remove_account(self):
        selected_items = self.account_list.selectedItems()
        
        if not selected_items:
            QMessageBox.warning(self, "警告", "请先选择一个账户")
            return
            
        name = selected_items[0].text()
        
        # 检查该账户是否被使用
        self.db.cursor.execute("SELECT COUNT(*) FROM transactions WHERE account=?", (name,))
        count = self.db.cursor.fetchone()[0]
        if count > 0:
            QMessageBox.warning(
                self, "无法删除", 
                f"账户 '{name}' 已被使用，请先修改相关记录"
            )
            return
            
        reply = QMessageBox.question(
            self, "确认删除", 
            f"确定要删除账户 '{name}' 吗?",
            QMessageBox.Yes | QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            # 从数据库删除账户
            self.db.delete_account(name)
            
            # 更新本地数据
            self.accounts = self.db.get_accounts()
            
            # 更新UI
            self.account_list.clear()
            self.account_list.addItems(self.accounts)
            self.account_combo.clear()
            self.account_combo.addItems(self.accounts)
            self.filter_account_combo.clear()
            self.filter_account_combo.addItems(["所有账户"] + self.accounts)
            
            QMessageBox.information(self, "成功", f"账户 '{name}' 已删除")
    
    def show_about(self):
        about_text = (
            "<b>本地记账工具 v1.6</b><br><br>"
            "一个简单实用的个人财务管理工具<br><br>"
            "功能包括：<br>"
            "- 记录收入和支出<br>"
            "- 按分类、账户管理交易<br>"
            "- 图表分析收支情况<br>"
            "- 导出/导入CSV数据<br>"
            "- 使用SQLite数据库存储数据<br>"
            "- 多主题切换功能<br><br>"
            "© 2025 本地记账工具开发者"
        )
        
        QMessageBox.about(self, "关于本地记账工具", about_text)
    
    def closeEvent(self, event):
        """窗口关闭时断开数据库连接"""
        self.db.disconnect()
        event.accept()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 设置应用样式
    app.setStyle("Fusion")
    
    # 创建主窗口
    window = FinanceManagerApp()
    window.show()
    
    # 初始化表格数据
    window.update_table()
    
    sys.exit(app.exec_())